package second.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution10 {

    List<String> res = new ArrayList<>();

    List<String> tmp = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        back(0, s);
        return res;
    }

    public void back(int index, String s) {
        if (tmp.size() == 4 && index == s.length()) {
            StringBuffer sb = new StringBuffer();
            for (String str : tmp) {
                sb.append(str).append('.');
            }
            sb.deleteCharAt(sb.length() - 1);
            res.add(sb.toString());
            return;
        }
        if (tmp.size() >= 4) return;
        if (index >= s.length()) return;
        for (int i = index; i < s.length(); i++) {
            if (isIPAddr(s.substring(index, i + 1))) {
                tmp.add(s.substring(index, i + 1));
                back(i + 1, s);
                tmp.remove(tmp.size() - 1);
            }
        }
    }

    public boolean isIPAddr(String s) {
        if (s.length() > 1 && s.charAt(0) == '0') return false;
        if (s.length() > 3) return false;
        int i = Integer.parseInt(s);
        return i >= 0 && i <= 255;
    }
}
